<template>
	<el-drawer v-model="visibleDialog" class="custom-adrawer" size="100%" @close="handleCancel">
		<template #header>
			<div class="flex flex-pack-justify flex_align-center">
				<span>查看详情</span>
				<el-button type="primary" @click="saveDesignEv">保存</el-button>
			</div>
		</template>
		<div>
			<er-form-editor
				v-if="myProps.modelValue"
				ref="EReditorRef"
				:is-show-i18n="false"
				:file-upload-u-r-i="uploadFileApi"
				@listener="handleListener"
			/>
		</div>
	</el-drawer>
</template>

<script setup>
import { computed, ref, watch, nextTick } from 'vue'
import { erFormEditor } from '@ER/formEditor'
import { ElMessage } from 'element-plus'
import formtemplate from '@/api/flow/formtemplate'
const { VITE_APP_BASE_API } = import.meta.env
const EReditorRef = ref()
const formOptions = ref({})
const uploadFileApi = ref(`${VITE_APP_BASE_API}/v1/oss/upload`)

console.log('erFormEditor')
console.log(erFormEditor)

// 同步值
const $myEmit = defineEmits(['update:modelValue', 'successFn'])

const myProps = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	record: {
		type: Object,
		default: () => {}
	}
})

const handleListener = obj => {}

const handleCancel = () => {
	$myEmit('update:modelValue', false)
}

const saveDesignEv = async () => {
	console.log(EReditorRef.value)
	const formStructure = EReditorRef.value.getData()
	const fields = formStructure?.fields || []
	console.log('fields')
	console.log(fields)
	const bool = fields.length
	if (!bool) {
		return ElMessage({
			message: '请设计您的表单模板内容',
			type: 'error'
		})
	}
	const content = JSON.stringify(formStructure)
	await formtemplate.formTemplateAddOrEditSaveApi({ ...myProps.record, content })
	ElMessage.success(`表单模板设计成功~`)
	handleCancel()
	$myEmit('successFn')
}

// computed
const visibleDialog = computed({
	get() {
		return myProps.modelValue
	},
	set(val) {
		$myEmit('update:modelValue', val)
	}
})

watch(
	() => myProps.modelValue,
	(val, oldValue) => {
		if (val) {
			nextTick(() => {
				if (myProps.record?.content) {
					const formStructure = JSON.parse(myProps.record.content || '{}')
					EReditorRef.value.setData(formStructure || {})
				}
			})
		}
	}
)
</script>

<style scoped lang="scss">
.flow-header-box {
	font-weight: 400;
	font-size: 14px;
	border-bottom: 1px solid #e5e6ec;
	padding: 0 16px;
	height: 39px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	color: #86909c;
}

//.custom-adrawer {
//	&:deep(.el-drawer) {
//		.el-drawer__header {
//			background-color: rgb(245, 245, 245);
//			padding: 0px 20px;
//			height: 50px;
//			color: #000000;
//			margin-bottom: 0px;
//		}
//		.el-drawer__title {
//			font-size: 20px;
//		}
//	}
//}
:deep(.el-drawer) {
	.el-drawer__header {
		background-color: rgb(245, 245, 245);
		padding: 0px 20px;
		height: 50px;
		color: #000000;
		margin-bottom: 0px;
	}
	.el-drawer__title {
		font-size: 20px;
	}
}
</style>
